/*
 *  Class name: ManagersHandler.java
 *  Version: 1.0
 *  Date: 4.6.2014
 */
package cz.muni.fi.pv168.addressbook.daos.impl.handler;

import cz.muni.fi.pv168.addressbook.daos.AddressBookManager;
import cz.muni.fi.pv168.addressbook.daos.ContactManager;
import cz.muni.fi.pv168.addressbook.daos.PersonManager;
import cz.muni.fi.pv168.addressbook.daos.impl.AddressBookManagerImpl;
import cz.muni.fi.pv168.addressbook.daos.impl.ContactManagerImpl;
import cz.muni.fi.pv168.addressbook.daos.impl.PersonManagerImpl;
import cz.muni.fi.pv168.addressbook.entities.Contact;
import cz.muni.fi.pv168.addressbook.entities.Person;
import java.util.List;

/**
 *
 * @author Michal Ďuriš
 */
public class ManagersHandler {

    private PersonManager personManager;
    private ContactManager contactManager;

    private AddressBookManager addressBookManager;

    private ManagersHandler() {
    }

    private void init() throws Exception {

        personManager = PersonManagerImpl.getInstance();
        contactManager = ContactManagerImpl.getInstance();

        addressBookManager = new AddressBookManagerImpl(personManager,
                contactManager);

    }

    public static ManagersHandler getInstance() throws Exception {

        final ManagersHandler handler = new ManagersHandler();
        handler.init();

        return handler;
    }

    public void createPerson(Person person) {
        personManager.createPerson(person);
    }

    public void updatePerson(Person person) {
        personManager.updatePerson(person);
    }

    public void deletePerson(Person person) {

        personManager.deletePerson(person);

        try {

            contactManager.removeContactsFromPerson(addressBookManager
                    .getAllContactsOfPerson(person));

        } catch (RuntimeException ex) {

            personManager.createPerson(person);

            throw new RuntimeException(ex);
        }
    }

    public List<Person> getAllPersons() {
        return personManager.getAllPersons();
    }

    public List<Person> findPerson(String searchString) {
        return personManager.findPerson(searchString);
    }

    public void addContactToPerson(Contact contact) {
        contactManager.addContactToPerson(contact);
    }

    public void updateContact(Contact contact) {
        contactManager.updateContact(contact);
    }

    public void removeContactFromPerson(Contact contact) {
        contactManager.removeContactFromPerson(contact);
    }

    public List<Contact> getAllContacts() {
        return contactManager.getAllContacts();
    }

    public List<Contact> getAllContactsOfPerson(Person person) {
        return addressBookManager.getAllContactsOfPerson(person);
    }

    public List<Person> findContact(String searchString) {
        return addressBookManager.findContact(searchString);
    }

}
